/*
 * Copyright (c) 2018. J4dream Created.
 */

package com.j4dream.property.web.user.controller;

import com.google.common.collect.ImmutableMap;
import com.j4dream.property.config.ConstConfig;
import com.j4dream.property.dao.UserDao;
import com.j4dream.property.model.UserDto;
import com.j4dream.property.service.CacheService;
import com.j4dream.property.service.EmailService;
import com.j4dream.property.util.ID;
import com.j4dream.property.web.user.ForgotPassVo;
import com.j4dream.property.web.user.ResetPassVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

import java.util.concurrent.TimeUnit;

import static org.springframework.http.ResponseEntity.ok;

@RestController()
@RequestMapping("/public-api")
public class ForgotPassController {

    @Autowired
    private UserDao userDao;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @PostMapping("/forgot-pass")
    public ResponseEntity forgotPass(@RequestBody @Valid ForgotPassVo forgotPassVo) {
        String email = forgotPassVo.getEmail();
        UserDto u = userDao.findOneByEmail(email);
        if (u == null) {
            return ok(ImmutableMap.of("error", "No user."));
        }
        String token = ID.get();
        String cacheKey = String.format(ConstConfig.CHANGE_USER_PASSWORD, token);
        cacheService.setValue(cacheKey, u.getEmail());
        cacheService.setExpire(cacheKey,24, TimeUnit.HOURS);
        emailService.sendResetPasswordEmail(email, token);
        return ok(0);
    }

    @PutMapping("/reset-pass")
    public ResponseEntity resetPass(@RequestBody @Valid ResetPassVO resetPassVO) {
        String key = String.format(String.format(ConstConfig.CHANGE_USER_PASSWORD, resetPassVO.getToken()));
        String email = cacheService.getValue(key);
        if (email == null) {
            return ok(ImmutableMap.of("error", "Invaid token"));
        }
        UserDto u = userDao.findOneByEmail(email);
        if (u == null) {
            return ok(ImmutableMap.of("error", "Invaid user"));
        }
        userDao.updatePassByEmail(passwordEncoder.encode(resetPassVO.getPassword()), email);
        cacheService.delKey(key);
        return ok(0);
    }
}
